package com.cqndt.disaster.device.service.impl;

import java.util.Map;
import java.util.HashMap;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.slf4j.LoggerFactory;
import com.iotplatform.client.dto.*;
import com.iotplatform.client.NorthApiClient;
import org.springframework.stereotype.Service;
import com.iotplatform.client.NorthApiException;
import com.cqndt.disaster.device.common.util.AuthUtil;
import com.cqndt.disaster.device.service.ContrlService;
import com.iotplatform.client.invokeapi.Authentication;
import com.iotplatform.client.invokeapi.SignalDelivery;
import com.iotplatform.client.invokeapi.DeviceManagement;
import org.springframework.scheduling.annotation.Scheduled;
import com.cqndt.disaster.device.common.enums.ConstantErrorEnum;
import com.cqndt.disaster.device.common.exception.ContrlException;

/**
 * Created By marc
 * Date: 2019/5/7  19:17
 * Description:
 **/
@Service
public class ContrlServiceImpl implements ContrlService {

    private org.slf4j.Logger logger = LoggerFactory.getLogger(getClass());

    private SignalDelivery signalDelivery = null;
    private String accessToken = "";
    @SuppressWarnings("unused")
	private DeviceManagement deviceManagement = null;

    //定时刷新token
    @Scheduled(initialDelay = 100, fixedDelay = 1800000)
    public void refreshToken() {
        Properties p = new Properties();
        InputStream keycert = AuthUtil.class.getClassLoader().getResourceAsStream("tianyi/tianyi.properties");
        try {
            NorthApiClient northApiClient = AuthUtil.initApiClient();
            signalDelivery = new SignalDelivery(northApiClient);
            deviceManagement = new DeviceManagement(northApiClient);
            Authentication authentication = new Authentication(northApiClient);
            AuthOutDTO authOutDTO = authentication.getAuthToken();
            AuthRefreshInDTO authRefreshInDTO = new AuthRefreshInDTO();
            p.load(keycert);
            authRefreshInDTO.setAppId(p.getProperty("appId").trim());
            authRefreshInDTO.setSecret(northApiClient.getClientInfo().getSecret());
            String refreshToken = authOutDTO.getRefreshToken();
            authRefreshInDTO.setRefreshToken(refreshToken);
            AuthRefreshOutDTO authRefreshOutDTO = authentication.refreshAuthToken(authRefreshInDTO);
            accessToken = authRefreshOutDTO.getAccessToken();
        } catch (NorthApiException | IOException e1) {
            System.out.println("定时刷新token:");
            e1.printStackTrace();
        } finally {
            if (keycert != null) {
                try {
                    keycert.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    @Override
    public PostDeviceCommandOutDTO2 postCommand(String deviceId, String payload) {
        logger.debug(deviceId+"发送指令: " + payload);
        PostDeviceCommandInDTO2 pdcInDTO = new PostDeviceCommandInDTO2();
        pdcInDTO.setDeviceId(deviceId);
        pdcInDTO.setExpireTime(0);

        CommandDTOV4 cmd = new CommandDTOV4();
        cmd.setServiceId("GasMeterStream");
        cmd.setMethod("DOWNLINK");
        Map<String, Object> cmdParam = new HashMap<>();
        cmdParam.put("payload", payload);

        cmd.setParas(cmdParam);
        pdcInDTO.setCommand(cmd);

        try {
            return signalDelivery.postDeviceCommand(pdcInDTO, null, accessToken);
        } catch (NorthApiException e) {
            if ("1003".equals(e.getError_code())) {
                throw new ContrlException(ConstantErrorEnum.CONNENT_TIME_OUT);
            }
           logger.error(e.toString());
        }
        return null;
    }
}